package com.ttl.bc.ap.debitnote2.db;

import hibernate.util.HibernateUtil;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import com.ttl.bc.ap.ap.bean.BCAPBean;
import com.ttl.bc.ap.debitnote2.bean.BCDebitNote2;
import com.ttl.bc.ap.debitnote2.bean.BCDebitNoteSub2;
import com.ttl.bc.ap.debitnote2.bean.BCInvDebitNote2;
import com.ttl.bc.ap.invoice.bean.ITTL_P2;
import com.ttl.bc.gl.trans.bean.BCTrans;
import com.ttl.bc.gl.trans.bean.BCTransSub;
import com.ttl.bc.processstock.bean.ProcessStockBean;
import com.ttl.bc.vat.inputtax.bean.BCInputTaxBean;
import com.ttl.common.db.ADAO;
import com.ttl.common.util.CommonUtils;

public class BCDebitNote2DAO extends ADAO {

	@SuppressWarnings("unchecked")
	public boolean deleteDN(String docNo) {
		String[] item_of_service = {"A-01", "A-02", "C-3",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E", "EXPORT",
				"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
				"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
				"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
				"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO", 
				"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
		Session session = null;

		try {
			sessionFactory = HibernateUtil.getSessionFactory();
			 session = sessionFactory.openSession();
			session.beginTransaction();

            org.hibernate.Query q = session.createQuery("FROM BCDebitNote2 WHERE docNo = '"+docNo+"'");
            List resultList = q.list();	
            for(int i=0; i<resultList.size(); i++){
            	BCDebitNote2 dn = (BCDebitNote2)resultList.get(i);
            	dn.setIsCancel(1);
            	
            	Iterator it = dn.getBcDebitNoteSub2s().iterator();
            	while (it.hasNext()) {
            		BCDebitNoteSub2 sub = (BCDebitNoteSub2) it.next();
					sub.setIsCancel(1);			
					
					//----------
					// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
					//ProcessStockDAO p = new ProcessStockDAO();	
											
					boolean isItemService = false;
					for (int ip = 0; ip < item_of_service.length; ip++) {
						if(item_of_service[ip].contains(sub.getItemCode())) {
							isItemService = true;
						}				
					}
					if(isItemService==false) {
			        	ProcessStockBean bean = new ProcessStockBean();
			        	bean.setItemCode(sub.getItemCode());
			        	bean.setDocDate(sub.getDocDate());
			        	bean.setProcessFlag(0);
			        	bean.setFlowStatus(1);
			        	bean.setProcessType(7);//	สำหรับเพิ่มหนี้
			        	bean.setProcessCase(2);//  บันทึกเอกสารให้ =1, แก้ไขเอกสารให้=2,ลบเอกสารให้=3
			        		        	
			        	session.save(bean);
			        	
			    		System.out.println(CommonUtils.getDateTimeForStamp()+" #use :ProcessStockDAO #mode :add "+
			  				  "#item:"+sub.getItemCode());
//			 				BCWinService จะ update: lastBuyPrice ให้กับ item ที่ซื้อเข้ามา แบบ auto อยู่แล้ว	
//				    		new BCItemDAO().updateLastBuyPrice(sub.getItemCode(),sub.getPrice());
					}
            	}
            	
            	it = dn.getBcInvDebitNote2s().iterator();
            	while (it.hasNext()) {
					BCInvDebitNote2 invDN = (BCInvDebitNote2) it.next();
					invDN.setIsCancel(1);
				}

    			org.hibernate.Query q2 = session.createQuery("FROM BCAPBean WHERE code ='"+dn.getApCode()+"'");
                List resultList2 = q2.list();
                
                if (resultList2!=null && resultList2.size()>0) {		            
                	BCAPBean h = (BCAPBean)resultList2.get(0);
                	
                	System.out.println("\nbefore h.getDebtAmount()="+h.getDebtAmount());
                	
                	if(docNo.contains("CN")) {//ถ้ายกเลิกเอกสารลดหนี้ ต้องเอายอดนั้นไป  '+' เข้า กับยอดหนี้ด้วย
                		h.setDebtAmount(h.getDebtAmount()+dn.getSumOfTotalTax());
                	}else if(docNo.contains("DN")) {//ถ้ายกเลิกเอกสารเพิ่มหนี้ ต้องเอายอดนั้นไป  '-' เข้า กับยอดหนี้ด้วย
                		h.setDebtAmount(h.getDebtAmount()-dn.getSumOfTotalTax());
                	}
                	
                	System.out.println("after  h.getDebtAmount()="+h.getDebtAmount());
                	session.save(h);
                }
                
            	session.save(dn);
            }

            q = session.createQuery("FROM BCInputTaxBean WHERE docNo = '"+docNo+"'");
            resultList = q.list();	
            for(int i=0; i<resultList.size(); i++){
            	BCInputTaxBean tax = (BCInputTaxBean)resultList.get(i);
            	tax.setShortTaxDesc("ยกเลิก");
            	tax.setBeforeTaxAmount(0d);
            	tax.setTaxAmount(0d);
            	session.save(tax);
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #use :BCInputTaxBean #cancel "+
		  				  "#docNo:"+tax.getDocNo());            	            	
            }

            q = session.createQuery("FROM BCTrans WHERE docNo = '"+docNo+"'");
            resultList = q.list();	
            for(int i=0; i<resultList.size(); i++){
            	BCTrans t = (BCTrans)resultList.get(i);
            	t.setMyDescription("ยกเลิก");
            	t.setIsCancel(1);
            	session.save(t);
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #use :BCTrans #cancel "+
		  				  "#docNo:"+t.getDocNo());            	
            }

            q = session.createQuery("FROM BCTransSub WHERE docNo = '"+docNo+"'");
            resultList = q.list();	
            for(int i=0; i<resultList.size(); i++){
            	BCTransSub tsub = (BCTransSub)resultList.get(i);
            	session.delete(tsub);
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #use :BCTransSub #delete "+
		  				  "#docNo:"+tsub.getDocNo());             	
            }
            
            q = session.createQuery("FROM ITTL_P2 WHERE docNo = '"+docNo+"'");
            resultList = q.list();	
            for(int i=0; i<resultList.size(); i++){
            	ITTL_P2 p2 = (ITTL_P2)resultList.get(i);
            	p2.setIsCancel(1);
            	session.save(p2);
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #use :ITTL_P2 #cancel "+
		  				  "#docNo:"+docNo);            	            	
            } 		
			
			session.getTransaction().commit();
			return true;
		}catch(Exception e) {
			System.out.println(e.toString());
			return false;
		}finally {
			session.close();
		}
	}
}
